import express, { Request, Response, Router } from 'express';
import { PrismaClient } from '@prisma/client';
import { adminAuthMiddleware, requireAdmin } from '../../middleware/adminAuth';
import { ResponseHelper } from '../../utils/response';

const router: Router = express.Router();
const prisma = new PrismaClient();

// 所有推荐人管理路由都需要管理员认证（包括 PARTNER）
router.use(adminAuthMiddleware);

// 获取推荐人列表
router.get('/list', async (req: Request, res: Response): Promise<void> => {
  try {
    const { page = 1, limit = 20, search = '', exportAll = 'false' } = req.query;
    const skip = (Number(page) - 1) * Number(limit);

    // 获取当前登录用户信息
    const userType = (req as any).userType;
    const currentUserId = (req as any).userId;
    const adminId = (req as any).adminId;
    const adminRole = (req as any).adminRole;
    const isPartner = (req as any).isPartner;

    // 构建搜索条件
    const where: any = {
      referredUsers: {
        some: {} // 只获取有推荐下线的用户
      }
    };

    if (search) {
      where.OR = [
        { referralCode: { contains: String(search) } },
        { name: { contains: String(search) } },
        { idNumber: { contains: String(search) } }
      ];
    }

    // 权限过滤：USER角色和PARTNER角色只能查看自己邀请的推荐人
    if (userType === 'USER' && currentUserId) {
      // 推荐人只能看到自己邀请的那些有下线的用户（即自己邀请的推荐人）
      where.referredBy = currentUserId;
    } else if (userType === 'ADMIN' && adminRole === 'PARTNER' && isPartner && adminId) {
      // 合作伙伴只能看到自己邀请的推荐人
      where.partnerAdminId = adminId;
    }

    // 判断是否导出全部
    const isExportAll = exportAll === 'true';

    // 获取推荐人列表
    const referrers = await prisma.user.findMany({
      where,
      select: {
        id: true,
        referralCode: true,
        name: true,
        idNumber: true,
        createdAt: true,
        _count: {
          select: {
            referredUsers: true // 推荐人数
          }
        },
        referredUsers: {
          select: {
            id: true,
            name: true,
            createdAt: true
          },
          take: 5 // 只显示前5个推荐用户
        }
      },
      orderBy: {
        createdAt: 'desc'
      },
      ...(isExportAll ? {} : {
        skip,
        take: Number(limit)
      })
    });

    // 获取总数
    const total = await prisma.user.count({ where });

    const pagination = {
      page: Number(page),
      limit: Number(limit),
      total,
      totalPages: Math.ceil(total / Number(limit))
    };

    // 格式化日期对象
    const formattedReferrers = referrers.map(referrer => ({
      ...referrer,
      createdAt: referrer.createdAt.toISOString(),
      referredUsers: referrer.referredUsers.map(user => ({
        ...user,
        createdAt: user.createdAt.toISOString()
      }))
    }));

    ResponseHelper.success(res, {
      referrers: formattedReferrers,
      pagination
    }, '추천인 목록 조회에 성공했습니다.');
  } catch (error: any) {
    console.error('추천인 목록 조회에 실패했습니다.:', error);
    ResponseHelper.serverError(res, '추천인 목록 조회에 실패했습니다.', error);
  }
});

// 获取推荐设置 - 必须在 /:id 之前定义
router.get('/settings', adminAuthMiddleware, async (req: Request, res: Response): Promise<void> => {
  try {
    // 获取全局默认设置
    let globalSettings = await prisma.referralSettings.findFirst({
      where: { userId: null }
    });

    // 如果没有全局设置，创建默认设置
    if (!globalSettings) {
      globalSettings = await prisma.referralSettings.create({
        data: {
          userId: null,
          depositRate: 0.0050, // 0.5%
          stakingRate: 0.0100, // 1%
          isActive: true
        }
      });
    }

    // 获取所有用户特定设置
    const userSettings = await prisma.referralSettings.findMany({
      where: {
        userId: { not: null }
      },
      include: {
        user: {
          select: {
            id: true,
            name: true,
            referralCode: true
          }
        }
      }
    });

    // 转换 Decimal 对象为数字
    const formattedGlobalSettings = globalSettings ? {
      ...globalSettings,
      depositRate: Number(globalSettings.depositRate),
      stakingRate: Number(globalSettings.stakingRate)
    } : null;

    const formattedUserSettings = userSettings.map(setting => ({
      ...setting,
      depositRate: Number(setting.depositRate),
      stakingRate: Number(setting.stakingRate)
    }));

    ResponseHelper.success(res, {
      global: formattedGlobalSettings,
      users: formattedUserSettings
    }, '추천 설정 조회에 성공했습니다.');
  } catch (error: any) {
    console.error('추천 설정 조회에 실패했습니다.:', error);
    ResponseHelper.serverError(res, '추천 설정 조회에 실패했습니다.', error);
  }
});

// 更新全局推荐设置 - 仅管理员可操作
router.put('/settings/global', requireAdmin, async (req: Request, res: Response): Promise<void> => {
  try {
    const { depositRate, stakingRate, isActive } = req.body;

    // 验证参数
    if (depositRate !== undefined && (depositRate < 0 || depositRate > 1)) {
      ResponseHelper.error(res, '충전 추천 비율은 0~100% 사이여야 합니다.');
      return;
    }

    if (stakingRate !== undefined && (stakingRate < 0 || stakingRate > 1)) {
      ResponseHelper.error(res, '스테이킹 추천 비율은 0~100% 사이여야 합니다.');
      return;
    }

    // 获取或创建全局设置
    let settings = await prisma.referralSettings.findFirst({
      where: { userId: null }
    });

    if (settings) {
      // 更新现有设置
      settings = await prisma.referralSettings.update({
        where: { id: settings.id },
        data: {
          depositRate: depositRate !== undefined ? depositRate : undefined,
          stakingRate: stakingRate !== undefined ? stakingRate : undefined,
          isActive: isActive !== undefined ? isActive : undefined
        }
      });
    } else {
      // 创建新设置
      settings = await prisma.referralSettings.create({
        data: {
          userId: null,
          depositRate: depositRate || 0.0050,
          stakingRate: stakingRate || 0.0100,
          isActive: isActive !== undefined ? isActive : true
        }
      });
    }

    // 转换 Decimal 对象为数字
    const formattedSettings = {
      ...settings,
      depositRate: Number(settings.depositRate),
      stakingRate: Number(settings.stakingRate)
    };

    ResponseHelper.success(res, formattedSettings, '전체 추천 설정이 성공적으로 업데이트되었습니다.');
  } catch (error: any) {
    console.error('전체 추천 설정 업데이트에 실패했습니다.:', error);
    ResponseHelper.serverError(res, '전체 추천 설정 업데이트에 실패했습니다.', error);
  }
});

// 设置特定用户的推荐比例 - 仅管理员可操作
router.post('/settings/user', requireAdmin, async (req: Request, res: Response): Promise<void> => {
  try {
    const { userId, depositRate, stakingRate, isActive } = req.body;

    if (!userId) {
      ResponseHelper.error(res, '사용자 ID는 비워둘 수 없습니다.');
      return;
    }

    // 验证用户是否存在
    const user = await prisma.user.findUnique({
      where: { id: Number(userId) }
    });

    if (!user) {
      ResponseHelper.notFound(res, '사용자를 찾을 수 없습니다.');
      return;
    }

    // 验证参数
    if (depositRate !== undefined && (depositRate < 0 || depositRate > 1)) {
      ResponseHelper.error(res, '충전 추천 비율은 0~100% 사이여야 합니다.');
      return;
    }

    if (stakingRate !== undefined && (stakingRate < 0 || stakingRate > 1)) {
      ResponseHelper.error(res, '스테이킹 추천 비율은 0~100% 사이여야 합니다.');
      return;
    }

    // 查找或创建用户特定设置
    let settings = await prisma.referralSettings.findFirst({
      where: { userId: Number(userId) }
    });

    if (settings) {
      // 更新现有设置
      settings = await prisma.referralSettings.update({
        where: { id: settings.id },
        data: {
          depositRate: depositRate !== undefined ? depositRate : undefined,
          stakingRate: stakingRate !== undefined ? stakingRate : undefined,
          isActive: isActive !== undefined ? isActive : undefined
        }
      });
    } else {
      // 创建新设置
      settings = await prisma.referralSettings.create({
        data: {
          userId: Number(userId),
          depositRate: depositRate || 0.0050,
          stakingRate: stakingRate || 0.0100,
          isActive: isActive !== undefined ? isActive : true
        }
      });
    }

    // 转换 Decimal 对象为数字
    const formattedSettings = {
      ...settings,
      depositRate: Number(settings.depositRate),
      stakingRate: Number(settings.stakingRate)
    };

    ResponseHelper.success(res, formattedSettings, '사용자 추천 비율이 성공적으로 설정되었습니다.');
  } catch (error: any) {
    console.error('사용자 추천 비율 설정에 실패했습니다.:', error);
    ResponseHelper.serverError(res, '사용자 추천 비율 설정에 실패했습니다.', error);
  }
});

// 删除特定用户设置（恢复使用全局设置） - 仅管理员可操作
router.delete('/settings/user/:userId', requireAdmin, async (req: Request, res: Response): Promise<void> => {
  try {
    const { userId } = req.params;

    await prisma.referralSettings.deleteMany({
      where: { userId: Number(userId) }
    });

    ResponseHelper.success(res, null, '사용자 개별 설정을 성공적으로 삭제했습니다.');
  } catch (error: any) {
    console.error('사용자 설정 삭제에 실패했습니다.:', error);
    ResponseHelper.serverError(res, '사용자 설정 삭제에 실패했습니다.', error);
  }
});

// 获取推荐统计数据
router.get('/stats', async (req: Request, res: Response): Promise<void> => {
  try {
    // 获取当前登录用户信息
    const userType = (req as any).userType;
    const currentUserId = (req as any).userId;
    const adminId = (req as any).adminId;
    const adminRole = (req as any).adminRole;
    const isPartner = (req as any).isPartner;

    // 构建过滤条件
    let userWhereCondition: any = undefined;

    // 权限过滤：USER角色和PARTNER角色只能查看自己邀请的推荐人统计
    if (userType === 'USER' && currentUserId) {
      userWhereCondition = { partnerAdminId: currentUserId };
    } else if (userType === 'ADMIN' && adminRole === 'PARTNER' && isPartner && adminId) {
      userWhereCondition = { partnerAdminId: adminId };
    }

    // 总推荐人数（有下线的用户）
    const totalReferrers = await prisma.user.count({
      where: {
        ...userWhereCondition,
        referredUsers: {
          some: {}
        }
      }
    });

    // 总被推荐用户数
    const totalReferred = await prisma.user.count({
      where: {
        ...userWhereCondition,
        referredBy: { not: null }
      }
    });

    // 今日新增推荐用户
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    const todayReferred = await prisma.user.count({
      where: {
        ...userWhereCondition,
        referredBy: { not: null },
        createdAt: { gte: today }
      }
    });

    // 推荐奖励总金额 - 如果是 PARTNER，需要过滤只查看自己邀请用户的奖励
    let rewardWhere: any = {};
    let stakingRewardWhere: any = {};

    if (userType === 'USER' && currentUserId) {
      const referredUserIds = (await prisma.user.findMany({
        where: { referredBy: currentUserId },
        select: { id: true }
      })).map(u => u.id);
      rewardWhere.userId = { in: referredUserIds };
      stakingRewardWhere.userId = { in: referredUserIds };
    } else if (userType === 'ADMIN' && adminRole === 'PARTNER' && isPartner && adminId) {
      const partnerUserIds = (await prisma.user.findMany({
        where: { partnerAdminId: adminId },
        select: { id: true }
      })).map(u => u.id);
      rewardWhere.userId = { in: partnerUserIds };
      stakingRewardWhere.userId = { in: partnerUserIds };
    }

    const totalRewards = await prisma.referralReward.aggregate({
      _sum: {
        amount: true
      },
      where: rewardWhere
    });

    const totalStakingRewards = await prisma.stakingReferralReward.aggregate({
      _sum: {
        amount: true
      },
      where: stakingRewardWhere
    });

    const stats = {
      totalReferrers,
      totalReferred,
      todayReferred,
      totalRewards: Number(totalRewards._sum.amount || 0),
      totalStakingRewards: Number(totalStakingRewards._sum.amount || 0)
    };

    ResponseHelper.success(res, stats, '추천 통계 조회에 성공했습니다.');
  } catch (error: any) {
    console.error('추천 통계 조회에 실패했습니다.:', error);
    ResponseHelper.serverError(res, '추천 통계 조회에 실패했습니다.', error);
  }
});

// 解除推荐关系 - 仅管理员可操作
router.post('/remove-relation', requireAdmin, async (req: Request, res: Response): Promise<void> => {
  try {
    const { userId, reason } = req.body;

    if (!userId) {
      ResponseHelper.error(res, '사용자 ID는 비워둘 수 없습니다.');
      return;
    }

    // 验证用户是否存在
    const user = await prisma.user.findUnique({
      where: { id: Number(userId) },
      include: {
        referrer: {
          select: {
            id: true,
            name: true,
            referralCode: true
          }
        }
      }
    });

    if (!user) {
      ResponseHelper.notFound(res, '사용자를 찾을 수 없습니다.');
      return;
    }

    if (!user.referredBy) {
      ResponseHelper.error(res, '해당 사용자는 추천 관계가 없습니다.');
      return;
    }

    // 记录原推荐人信息用于日志
    const originalReferrer = user.referrer;

    // 解除推荐关系 - 将 referredBy 设置为 null
    await prisma.user.update({
      where: { id: Number(userId) },
      data: {
        referredBy: null
      }
    });

    // 记录操作日志（简单控制台输出，后续可扩展为数据库记录）
    console.log(`[추천 관계 해제] 사용자 ${user.name}(ID:${user.id})와 추천인 ${originalReferrer?.name}(ID:${originalReferrer?.id})의 연결이 해제되었습니다.`, {
      operatorId: (req as any).admin?.id,
      reason: reason || '없음',
      timestamp: new Date().toISOString()
    });

    ResponseHelper.success(res, {
      userId: user.id,
      userName: user.name,
      originalReferrer: originalReferrer
    }, '추천 관계가 성공적으로 해제되었습니다.');
  } catch (error: any) {
    console.error('추천 관계 해제에 실패했습니다.:', error);
    ResponseHelper.serverError(res, '추천 관계 해제에 실패했습니다.', error);
  }
});

// 获取推荐收益提现申请列表
router.get('/withdraw/list', async (req: Request, res: Response): Promise<void> => {
  try {
    const {
      status,
      page = 1,
      limit = 20,
      startDate,
      endDate,
      userId,
      minAmount,
      maxAmount,
      exportAll = 'false' // 新增：导出全部数据参数
    } = req.query;

    // 获取当前登录用户信息
    const userType = (req as any).userType;
    const currentUserId = (req as any).userId;
    const adminId = (req as any).adminId;
    const adminRole = (req as any).adminRole;
    const isPartner = (req as any).isPartner;

    // 构建查询条件
    const where: any = {};

    if (status && status !== 'all') {
      where.status = status as string;
    }

    if (userId) {
      where.userId = parseInt(userId as string);
    }

    if (minAmount || maxAmount) {
      where.amountKrw = {};
      if (minAmount) where.amountKrw.gte = parseFloat(minAmount as string);
      if (maxAmount) where.amountKrw.lte = parseFloat(maxAmount as string);
    }

    if (startDate || endDate) {
      where.createdAt = {};
      if (startDate) where.createdAt.gte = new Date(startDate as string);
      if (endDate) {
        const endDateTime = new Date(endDate as string);
        endDateTime.setHours(23, 59, 59, 999);
        where.createdAt.lte = endDateTime;
      }
    }

    // 权限过滤：USER角色和PARTNER角色只能查看自己邀请的推荐人的收益提现
    if (userType === 'USER' && currentUserId) {
      // 推荐人只能看到自己邀请的用户的提现记录
      const referredUsers = await prisma.user.findMany({
        where: { referredBy: currentUserId },
        select: { id: true }
      });
      if (referredUsers.length === 0) {
        ResponseHelper.success(res, {
          records: [],
          summary: {
            pending: { count: 0, amount: 0 },
            confirmed: { count: 0, amount: 0 },
            failed: { count: 0, amount: 0 },
            cancelled: { count: 0, amount: 0 }
          },
          pagination: {
            page: Number(page),
            limit: Number(limit),
            total: 0,
            totalPages: 0
          }
        }, '추천 수익 출금 목록 조회에 성공했습니다.');
        return;
      }
      where.userId = { in: referredUsers.map(u => u.id) };
    } else if (userType === 'ADMIN' && adminRole === 'PARTNER' && isPartner && adminId) {
      // 合作伙伴只能看到自己邀请的用户的提现记录
      const partnerUsers = await prisma.user.findMany({
        where: { partnerAdminId: adminId },
        select: { id: true }
      });
      if (partnerUsers.length === 0) {
        ResponseHelper.success(res, {
          records: [],
          summary: {
            pending: { count: 0, amount: 0 },
            confirmed: { count: 0, amount: 0 },
            failed: { count: 0, amount: 0 },
            cancelled: { count: 0, amount: 0 }
          },
          pagination: {
            page: Number(page),
            limit: Number(limit),
            total: 0,
            totalPages: 0
          }
        }, '추천 수익 출금 목록 조회에 성공했습니다.');
        return;
      }
      where.userId = { in: partnerUsers.map(u => u.id) };
    }

    // 判断是否导出全部
    const isExportAll = exportAll === 'true';

    // 获取提现记录
    const withdrawals = await prisma.referralWithdrawRecord.findMany({
      where,
      include: {
        user: {
          select: {
            id: true,
            name: true,
            idNumber: true,
            mobileNumber: true,
            referralCode: true
          }
        }
      },
      orderBy: { createdAt: 'desc' },
      ...(isExportAll ? {} : {
        skip: (Number(page) - 1) * Number(limit),
        take: Number(limit)
      })
    });

    // 获取总记录数
    const total = await prisma.referralWithdrawRecord.count({ where });

    // 统计信息
    const summary = await prisma.referralWithdrawRecord.groupBy({
      by: ['status'],
      where: status && status !== 'all' ? {} : where,
      _count: {
        status: true
      },
      _sum: {
        amountKrw: true
      }
    });

    const statusSummary = {
      pending: { count: 0, amount: 0 },
      confirmed: { count: 0, amount: 0 },
      failed: { count: 0, amount: 0 },
      cancelled: { count: 0, amount: 0 }
    };

    summary.forEach(s => {
      const status = s.status.toLowerCase() as keyof typeof statusSummary;
      if (statusSummary[status]) {
        statusSummary[status].count = Number(s._count.status);
        statusSummary[status].amount = Number(s._sum.amountKrw) || 0;
      }
    });

    ResponseHelper.success(res, {
      records: withdrawals.map(w => ({
        ...w,
        amountKrw: Number(w.amountKrw),
        amountNear: Number(w.amountNear),
        nearPrice: Number(w.nearPrice)
      })),
      summary: statusSummary,
      pagination: {
        page: Number(page),
        limit: Number(limit),
        total: Number(total),
        totalPages: Math.ceil(Number(total) / Number(limit))
      }
    }, '추천 수익 출금 목록 조회에 성공했습니다.');
  } catch (error: any) {
    console.error('추천 수익 출금 목록 조회 오류:', error);
    ResponseHelper.serverError(res, '추천 수익 출금 목록 조회에 실패했습니다.', error);
  }
});

// 获取推荐收益提现申请详情
router.get('/withdraw/:id', async (req: Request, res: Response): Promise<void> => {
  try {
    const { id } = req.params;

    // 获取当前登录用户信息
    const userType = (req as any).userType;
    const currentUserId = (req as any).userId;
    const adminId = (req as any).adminId;
    const adminRole = (req as any).adminRole;
    const isPartner = (req as any).isPartner;

    const withdrawal = await prisma.referralWithdrawRecord.findUnique({
      where: { id: parseInt(id) },
      include: {
        user: {
          select: {
            id: true,
            name: true,
            idNumber: true,
            mobileNumber: true,
            referralCode: true,
            withdrawalBank: true,
            withdrawalAccount: true,
            accountHolder: true,
            referredBy: true,
            partnerAdminId: true,
            stakingInfo: {
              select: {
                lockedAmount: true
              }
            }
          }
        }
      }
    });

    if (!withdrawal) {
      ResponseHelper.notFound(res, '출금 기록이 존재하지 않습니다.');
      return;
    }

    // 权限检查：USER角色只能查看自己邀请的用户的提现记录
    if (userType === 'USER' && currentUserId) {
      if (withdrawal.user.referredBy !== currentUserId) {
        ResponseHelper.forbidden(res, '이 출금 기록을 조회할 권한이 없습니다.');
        return;
      }
    }
    // 权限检查：PARTNER角色只能查看自己邀请的用户的提现记录
    if (userType === 'ADMIN' && adminRole === 'PARTNER' && isPartner && adminId) {
      if (withdrawal.user.partnerAdminId !== adminId) {
        ResponseHelper.forbidden(res, '이 출금 기록을 조회할 권한이 없습니다.');
        return;
      }
    }

    ResponseHelper.success(res, {
      ...withdrawal,
      amountKrw: Number(withdrawal.amountKrw),
      amountNear: Number(withdrawal.amountNear),
      nearPrice: Number(withdrawal.nearPrice),
      user: {
        ...withdrawal.user,
        stakingInfo: withdrawal.user.stakingInfo ? {
          lockedAmount: Number(withdrawal.user.stakingInfo.lockedAmount)
        } : null
      }
    }, '출금 상세 조회에 성공했습니다.');
  } catch (error: any) {
    console.error('출금 상세 조회 오류:', error);
    ResponseHelper.serverError(res, '출금 상세 조회에 실패했습니다.', error);
  }
});

// 处理推荐收益提现申请（승인/거부） - 仅管理员可操作
router.post('/withdraw/:id/process', requireAdmin, async (req: Request, res: Response): Promise<void> => {
  try {
    const { id } = req.params;
    const { action, note } = req.body; // action: 'approve' | 'reject'
    const adminId = (req as any).adminId;
    const adminName = (req as any).adminName;

    if (!['approve', 'reject'].includes(action)) {
      ResponseHelper.error(res, '유효하지 않은 작업입니다. approve 또는 reject만 가능합니다.');
      return;
    }

    // 获取提现记录
    const withdrawal = await prisma.referralWithdrawRecord.findUnique({
      where: { id: parseInt(id) },
      include: {
        user: {
          select: {
            name: true,
            idNumber: true,
            stakingInfo: true
          }
        }
      }
    });

    if (!withdrawal) {
      ResponseHelper.notFound(res, '출금 기록이 존재하지 않습니다.');
      return;
    }

    if (withdrawal.status !== 'PENDING') {
      ResponseHelper.error(res, '해당 출금 신청은 이미 처리되어 다시 처리할 수 없습니다.');
      return;
    }

    if (action === 'approve') {
      // 승인提现：更新상태
      const result = await prisma.$transaction(async (tx) => {
        // 更新提现记录상态
        const updatedWithdrawal = await tx.referralWithdrawRecord.update({
          where: { id: parseInt(id) },
          data: {
            status: 'CONFIRMED',
            adminNote: note || `관리자 ${adminName}가 출금을 승인했습니다.`,
            processedBy: adminId,
            processedAt: new Date()
          }
        });

        // 注意：lockedAmount已经在用户申请时被扣除了，这里不需要再次操作
        // 管理员只需要线下转账给用户，然后标记为已确认即可

        return updatedWithdrawal;
      });

      ResponseHelper.success(res, {
        ...result,
        amountKrw: Number(result.amountKrw),
        amountNear: Number(result.amountNear),
        nearPrice: Number(result.nearPrice)
      }, `출금이 승인되었습니다: 사용자 ${withdrawal.user.name}에게 ${Number(withdrawal.amountKrw).toLocaleString('ko-KR')}원을 송금해 주세요.`);
    } else {
      // 거부提现：需要把lockedAmount退回给用户
      const result = await prisma.$transaction(async (tx) => {
        // 更新提现记录상태
        const updatedWithdrawal = await tx.referralWithdrawRecord.update({
          where: { id: parseInt(id) },
          data: {
            status: 'FAILED',
            adminNote: note || `관리자 ${adminName}가 출금을 거부했습니다.`,
            processedBy: adminId,
            processedAt: new Date()
          }
        });

        // 退回lockedAmount
        if (withdrawal.user.stakingInfo) {
          await tx.userStaking.update({
            where: { userId: withdrawal.userId },
            data: {
              lockedAmount: { increment: Number(withdrawal.amountNear) }
            }
          });
        }

        return updatedWithdrawal;
      });

      ResponseHelper.success(res, {
        ...result,
        amountKrw: Number(result.amountKrw),
        amountNear: Number(result.amountNear),
        nearPrice: Number(result.nearPrice)
      }, `출금 신청이 거부되었습니다: ${note || '거절 사유가 제공되지 않았습니다.'}`);
    }
  } catch (error: any) {
    console.error('출금 신청 처리 오류:', error);
    ResponseHelper.serverError(res, '출금 신청 처리에 실패했습니다.', error);
  }
});

// 获取推荐人详情和所有下线 (动态路由放在最后，避免拦截其他具体路由)
router.get('/:id', async (req: Request, res: Response): Promise<void> => {
  try {
    const { id } = req.params;
    const { page = 1, limit = 20 } = req.query;

    // 获取当前登录用户信息
    const userType = (req as any).userType;
    const currentUserId = (req as any).userId;
    const adminId = (req as any).adminId;
    const adminRole = (req as any).adminRole;
    const isPartner = (req as any).isPartner;

    // 验证id是否为有效数字
    const userId = Number(id);
    if (isNaN(userId) || userId <= 0) {
      ResponseHelper.error(res, '유효하지 않은 사용자 ID입니다.', 400);
      return;
    }

    const skip = (Number(page) - 1) * Number(limit);

    // 获取推荐人信息
    const referrer = await prisma.user.findUnique({
      where: { id: userId },
      select: {
        id: true,
        referralCode: true,
        name: true,
        idNumber: true,
        referredBy: true,
        partnerAdminId: true,
        createdAt: true,
        _count: {
          select: {
            referredUsers: true
          }
        }
      }
    });

    if (!referrer) {
      ResponseHelper.notFound(res, '추천인을 찾을 수 없습니다.');
      return;
    }

    // 权限检查：USER角色只能查看自己邀请的推荐人
    if (userType === 'USER' && currentUserId) {
      if (referrer.referredBy !== currentUserId) {
        ResponseHelper.forbidden(res, '이 추천인을 조회할 권한이 없습니다.');
        return;
      }
    }
    // 权限检查：PARTNER角色只能查看自己邀请的推荐人
    if (userType === 'ADMIN' && adminRole === 'PARTNER' && isPartner && adminId) {
      if (referrer.partnerAdminId !== adminId) {
        ResponseHelper.forbidden(res, '이 추천인을 조회할 권한이 없습니다.');
        return;
      }
    }

    // 获取推荐用户列表（分页）
    const referredUsers = await prisma.user.findMany({
      where: { referredBy: userId },
      select: {
        id: true,
        name: true,
        idNumber: true,
        createdAt: true,
        status: true,
        balance: {
          select: {
            total: true
          }
        }
      },
      orderBy: {
        createdAt: 'desc'
      },
      skip,
      take: Number(limit)
    });

    // 获取推荐用户总数
    const referredTotal = await prisma.user.count({
      where: { referredBy: Number(id) }
    });

    const pagination = {
      page: Number(page),
      limit: Number(limit),
      total: referredTotal,
      totalPages: Math.ceil(referredTotal / Number(limit))
    };

    // 格式化日期对象
    const formattedReferrer = {
      ...referrer,
      createdAt: referrer.createdAt.toISOString()
    };

    const formattedReferredUsers = referredUsers.map(user => ({
      ...user,
      createdAt: user.createdAt.toISOString(),
      balance: user.balance ? {
        total: Number(user.balance.total)
      } : { total: 0 }
    }));

    ResponseHelper.success(res, {
      referrer: formattedReferrer,
      referredUsers: formattedReferredUsers,
      pagination
    }, '추천인 상세 조회에 성공했습니다.');
  } catch (error: any) {
    console.error('추천인 상세 조회에 실패했습니다.:', error);
    ResponseHelper.serverError(res, '추천인 상세 조회에 실패했습니다.', error);
  }
});

export default router;
